package com.software.levelupserver.service.impl;

import com.software.levelupserver.entity.SecurityUserDetails;
import com.software.levelupserver.entity.User;
import com.software.levelupserver.service.UserService;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class SecurityUserDetailsService implements UserDetailsService {
    @Resource
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
        User user = userService.getUserByEmail(email);
        if(user == null){
            throw new UsernameNotFoundException("用户不存在");
        }
        //List<String> userPermissions = menuService.queryPermissionByUserId(user.getUserId());
        List<String> userPermissions = new ArrayList<>();
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        for (String userPermission : userPermissions) {
            SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(userPermission);
            authorities.add(simpleGrantedAuthority);
        }
        SecurityUserDetails securityUserDetails = new SecurityUserDetails(user);
        securityUserDetails.setAuthorities(authorities);
        return securityUserDetails;
    }
}

